<template>
    <div class="header" style="margin-bottom: 20px;">
        <div class="navbar bg-base-100">
            <div class="flex-1">
                <a class="btn btn-ghost normal-case text-xl" @click="addNetwork">LSR</a>
            </div>
            <div class="flex-none">

                <div class="dropdown dropdown-end" v-if="loginAddress.length == 0">
                    <label tabindex="0" class="btn btn-ghost btn-circle avatar">
                        <div class="w-10 rounded-full" @click="connectWallet">
                            <img :src="head" style="width: 100%; transform: scale(0.8);box-shadow: 0 0 10px 0 white;" />
                        </div>
                    </label>
                </div>

                <div class="dropdown dropdown-end" v-else>
                    <label tabindex="0" class="btn btn-ghost normal-case text-xl  m-1">
                        {{ loginAddress }}
                    </label>

                    <ul tabindex="0" for="logout"
                        class="menu menu-compact dropdown-content mt-3 p-2 shadow bg-base-100 rounded-box w-52">
                        <li>
                            <label class="justify-between" @click="logout">
                                <label for="my-modal">Disconnect</label>
                                <span class="badge">Notice</span>
                            </label>
                        </li>
                    </ul>
                </div>

            </div>

        </div>
    </div>
</template>

<script>
import { initializeWeb3 } from '../utils/LoveOnChain';
export default {


    name: "MyHead",
    data() {
        return {
            head: 'https://lh3.googleusercontent.com/QW0gZ3yugzXDvTANa5-cc1EpabQ2MGnl6enW11O6kIerEaBQGOhgyUOvhRedndD9io8RJMmJZfIXq1rMxUsFHS2Ttw=w128-h128-e365-rj-sc0x00ffffff',
            selectedFile: '', // 储存新上传的头像
            loginAddress: '',
            flag: false,
            web3: null,
            accounts: null,
            contractInstance: null
        }
    },
    async mounted() {
        const userInstance = await initializeWeb3();
        this.web3 = userInstance.web3;
        this.accounts = userInstance.accounts;
        this.contractInstance = userInstance.contractInstance;

        if (!this.web3) {
            console.log('Failed to initialize web3.');
            return;
        }

        // 进行其他初始化操作
        this.connectWallet();
    },
    methods: {
        async connectWallet() {
            if (window.ethereum) {
                try {
                    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                    console.log('已连接到 MetaMask 钱包');

                    this.web3.eth.defaultAccount = accounts[0];
                    console.log(accounts[0]);

                    const timestamp = localStorage.getItem('timestamp');
                    const signature = localStorage.getItem('signature');

                    if (timestamp && signature) {
                        const signer = await this.web3.eth.personal.ecRecover(timestamp, signature);

                        if (signer.toLowerCase() === this.web3.eth.defaultAccount.toLowerCase()) {
                            this.loginAddress = this.shortenAddress(this.web3.eth.defaultAccount, 4);
                            return;
                        } else {
                            console.log('签名验证失败！');
                        }
                    }

                    await this.signMessage(this.web3, accounts[0]);

                } catch (error) {
                    console.log('连接钱包失败:', error);
                }
            } else {
                console.log('未检测到 MetaMask 钱包');
            }
        },
        async signMessage(web3, account) {
            const timestamp = Date.now().toString();
            const signature = await web3.eth.personal.sign(timestamp, account, '');
            //在下面顺便对获取对签名进行验证签名 如果是就登陆成功
            const signer = await web3.eth.personal.ecRecover(timestamp, signature);
            // 检查 signer 地址是否与原始签名者地址匹配
            if (signer.toLowerCase() === account.toLowerCase()) {
                this.loginAddress = this.shortenAddress(account, 4);
                //如果说签名成功 我将签名的时间戳和签名的内容存入到本地
                localStorage.setItem('timestamp', timestamp);
                localStorage.setItem('signature', signature);
                //签名成功之后检测该账号余额是否有1eth
                const MIN_BALANCE = web3.utils.toWei('1', 'ether'); // 1 ETH
                const balance = await web3.eth.getBalance(account);
                if (web3.utils.toBN(balance).lt(web3.utils.toBN(MIN_BALANCE))) {
                    console.log('余额不足，正在充值...');
                    // 假设有一个中央账户可以发送ETH，你需要有一个私钥可以用来签署交易
                    const centralAccount = '0x0c174b3140b47B1Ef2686236Efa1591686F19681';
                    const privateKey = 'adc95b953256846bd55e7793ee4748cf5eb49f6c0a498f37ac69fbc98db03e84';

                    const transaction = {
                        to: account,
                        value: web3.utils.toHex(MIN_BALANCE - balance), // 为了充值至1 ETH
                        gas: 21000, // 足够支付一个普通的ETH转账
                    };
                    const signedTransaction = await web3.eth.accounts.signTransaction(transaction, privateKey);
                    await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
                    console.log('充值成功！');
                }
            } else {
                console.log('签名验证失败！');
            }
        },
        //对地址进行压缩
        shortenAddress(address, digits = 4) {
            if (!address) return '';
            return `${address.substring(0, digits + 2)}...${address.substring(address.length - digits)}`;
        },
        //创建一个方法将flag设置为相反值
        toggle() {
            this.flag = !this.flag;
        },

        //实现退出小狐狸钱包连接
        logout() {
            //清除本地缓存
            localStorage.removeItem('timestamp');
            localStorage.removeItem('signature');
            //清除当前账户
            this.loginAddress = '';
            //实现退出小狐狸钱包的连接
        },
        async addNetwork() {
            const provider = window.ethereum;
            try {
                // 提供关于新网络的信息
                const params = [{
                    chainId: '0x539', // 链的 ID，必须是十六进制的，且开头为 '0x'
                    chainName: 'LoveOnChain', // 链的名称
                    nativeCurrency: {
                        name: 'ETH',
                        symbol: 'ETH', // 货币符号，如 'ETH'
                        decimals: 18 // 货币小数位数
                    },
                    rpcUrls: ['HTTP://127.0.0.1:7545'], // JSON-RPC 的 URL
                    blockExplorerUrls: null // 区块浏览器的 URL
                }];

                // 请求用户添加新网络
                await provider.request({
                    method: 'wallet_addEthereumChain',
                    params,
                });
            } catch (error) {
                console.log(error);
            }
        }

    }
}
</script>

<style scoped>
.header {
    width: 81%;
    height: 9vh;
    border-radius: 10px;
    position: absolute;
    right: 5px;
    float: right;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}
</style>